
package net.qiqbframework.messaging;


import net.qiqbframework.messaging.task.MessageTask;

import java.util.Iterator;


public class DefaultInterceptorChain<T extends Message<?>> implements InterceptorChain {

    private final MessageHandler<? super T> handler;
    private final Iterator<? extends MessageHandlerInterceptor<? super T>> chain;
    private final MessageTask<? extends T> messageTask;


    public DefaultInterceptorChain(MessageTask<? extends T> messageTask,
                                   Iterable<? extends MessageHandlerInterceptor<? super T>> interceptors,
                                   MessageHandler<? super T> handler) {
        this.handler = handler;
        this.chain = interceptors.iterator();
        this.messageTask = messageTask;
    }

    @Override
    public Object proceed() throws Exception {
        if (chain.hasNext()) {
            return chain.next().handle(messageTask, this);
        } else {
            return handler.handle(messageTask.getMessage());
        }
    }
}
